package com.example.opengldemo.earth;

import android.content.res.Resources;
import android.opengl.GLES30;
import android.view.View;

import com.example.opengldemo.util.MatrixState;
import com.example.opengldemo.util.ShaderUtil;
import com.example.opengldemo.util.ShapeFactory;

import java.nio.FloatBuffer;

public class StarDemo {
    int mProgram ;

    String vertexShaderPath = "earth/vertex_xk.sh" ;
    String fragShaderPath = "earth/fragment_xk.sh" ;

    int m_A_PositionHandle ;
    String m_A_PositionHandle_Name ="aPosition";
    int m_U_PointSizehandle ;
    String m_U_PointSizehandle_Name ="uPointSize";
    int m_U_MVPMatrixhandle ;
    String m_U_MVPMatrixhandle_Name ="uMVPMatrix";

    float scale = 2;
    int vCount = 1000 ;

    float yAngle ;

    FloatBuffer vertexBuffer ;

    final float UNIT_SIZE = 10.0f ;

    public StarDemo(View view){
        initProgram(view) ;
        initBuffer() ;
    }



    public void initProgram(View view){
        Resources resources = view.getResources();
        String vertexRes = ShaderUtil.loadFromAssetsFile(vertexShaderPath , resources);
        ShaderUtil.checkGLError("==vv==");
        String fragRes = ShaderUtil.loadFromAssetsFile(fragShaderPath , resources);
        ShaderUtil.checkGLError("==ff==");
        if(vertexRes != null && fragRes != null){
            mProgram = ShaderUtil.createProgram(vertexRes , fragRes);
        }
        initHandle(mProgram);
    }

    private void initHandle(int program){
        m_A_PositionHandle = GLES30.glGetAttribLocation(program , m_A_PositionHandle_Name) ;
        m_U_MVPMatrixhandle = GLES30.glGetUniformLocation(program , m_U_MVPMatrixhandle_Name) ;
        m_U_PointSizehandle = GLES30.glGetUniformLocation(program , m_U_PointSizehandle_Name) ;
    }

    private void initBuffer() {

        float vertices[]=new float[vCount*3];
        for(int i=0;i<vCount;i++){
            double angleTempJD=Math.PI*2*Math.random();
            double angleTempWD=Math.PI*(Math.random()-0.5f);
            vertices[i*3]=(float)(UNIT_SIZE*Math.cos(angleTempWD)*Math.sin(angleTempJD));
            vertices[i*3+1]=(float)(UNIT_SIZE*Math.sin(angleTempWD));
            vertices[i*3+2]=(float)(UNIT_SIZE*Math.cos(angleTempWD)*Math.cos(angleTempJD));
        }

        vertexBuffer = ShapeFactory.getFloatBuffer(vertices);
    }
    public void drawSelf(){
        GLES30.glUseProgram(mProgram);
        GLES30.glUniformMatrix4fv(m_U_MVPMatrixhandle , 1 , false , MatrixState.getFinalMatrix() , 0);
        GLES30.glVertexAttribPointer(m_A_PositionHandle , 3  , GLES30.GL_FLOAT  , false , 3*4 , vertexBuffer);
        GLES30.glUniform1f(m_U_PointSizehandle , scale);

        GLES30.glEnableVertexAttribArray(m_A_PositionHandle);

        GLES30.glDrawArrays(GLES30.GL_POINTS , 0 , vCount);

        GLES30.glDisableVertexAttribArray(m_A_PositionHandle);
    }
}
